package club.info.security.config;

import club.info.security.service.CustomService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public CustomService customService() {
        return new CustomService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customService())
                .passwordEncoder(new BCryptPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/", "/login", "/logout", "/login.html").permitAll()
                .antMatchers("/normal/**").hasAnyRole("NORMAL", "VIP")
                .antMatchers("/vip/**").hasRole("VIP")
                .anyRequest().authenticated();

        http.formLogin() // 配置登录页
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .and()
                .rememberMe() //开启记住我功能
                .and()
                .logout() // 开启注销功能
                .logoutSuccessUrl("/") // 注销成功后跳转页面
                .and()
                .csrf().disable();// 关闭跨站请求,不关就会报错
    }
}
